package com.repairsystem.repairsys.websockt;

import com.repairsystem.repairsys.common.Const;
import com.repairsystem.repairsys.common.ResponseCode;
import com.repairsystem.repairsys.common.ServerResponse;
import com.repairsystem.repairsys.pojo.Admin;
import com.repairsystem.repairsys.pojo.Fault;
import com.repairsystem.repairsys.pojo.Maintainer;
import com.repairsystem.repairsys.pojo.User;
import com.repairsystem.repairsys.service.IAdminService;
import com.repairsystem.repairsys.service.IMaintainerService;
import com.repairsystem.repairsys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/{identity}/{id}")
@Component
@RestController
@CrossOrigin
//访问服务端的url地址
public class WebSocketServer {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IAdminService iAdminService;
    @Autowired
    private IMaintainerService iMaintainerService;


    private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<>();

    private Session session;
    private String id = "";
    private String identity = "";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(@PathParam(value = "identity") String identity,@PathParam(value = "id") String id, Session session) {
        this.session = session;
        this.id = id;//接收到发送消息的人员编号
        this.identity = identity;
        if(id != null){
            webSocketSet.put(identity+id, this);     //加入set中
            if (identity.equals("admin")) {
                lazySend(identity+id);
            }
            if(identity.equals("maintainer")){
                lazySend(identity+id);
            }
            System.out.println(identity+" "+id+"加入！");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(identity+id);  //从set中删除
        System.out.println("有一连接关闭！" );
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message) {
        try {
            sendtoUser(message,"admin");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 发送信息给指定ID用户，如果用户不在线则返回不在线信息给自己
     * @param message
     * @param sendAdmin
     * @throws IOException
     */
    public void sendtoUser(String message,String sendAdmin) throws IOException {
        if (sendAdmin != null) {
            if(sendAdmin.equals("admin")){
                for(String key : webSocketSet.keySet()) {
                    if(key.length() == 6 && key.substring(0,5).equals(sendAdmin)){
                        webSocketSet.get(key).sendMessage(message);
                        break;
                    }
                }
            }else if(sendAdmin.equals("maintainer")){
                for(String key : webSocketSet.keySet()) {
                    if(key.length() == 11 && key.substring(0,10).equals(sendAdmin)){
                        webSocketSet.get(key).sendMessage(message);
                    }
                }
            }

        }
    }

    public void lazySend(String key){
        try {
            webSocketSet.get(key).sendMessage("");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加待接受的故障
     * @param session
     * @return
     */
    @RequestMapping(value = "/user/user_place_order.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse userPlaceOrder(HttpSession session, Fault fault){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMassage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录");
        }
        ServerResponse response = iUserService.userPlaceOrder(fault);

        try {
            sendtoUser("","admin");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;
    }
    /**
     * 添加初步故障报修订单
     * @param session
     * @param faultId
     * @return
     */
    @RequestMapping(value = "/admin/add_tentative_fault_oder.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> addTentativeFaultOder(HttpSession session, String faultId){
        Admin admin = (Admin)session.getAttribute(Const.CURRENT_ADMIN);

        if(admin == null){
            return ServerResponse.createByErrorCodeMassage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录");
        }
        ServerResponse response = iAdminService.addTentativeFaultOder(faultId);
        try {
            sendtoUser("","maintainer");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 维修员接单
     * @return
     */
    @RequestMapping(value = "/maintainer/take_order.do",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse takeOrder(HttpSession session,String faultId,String maintainerId){
        Maintainer maintainer = (Maintainer) session.getAttribute(Const.CURRENT_MAINTAINER);

        if(maintainer == null){
            return ServerResponse.createByErrorCodeMassage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录");
        }
        ServerResponse response = iMaintainerService.takeOrder(faultId,maintainerId);
        try {
            sendtoUser("","maintainer");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}


